﻿(function () {
    "use strict";

    var channel;

    function subscribeToPushNotification() {
        var channelOperation = Windows.Networking.PushNotifications
            .PushNotificationChannelManager
            .createPushNotificationChannelForApplicationAsync()
            .then(function (newChannel) {
                channel = newChannel;

                // Insert the new channel URI into the Channel table.
                var client = getMobileServiceClient();
                var channelTable = client.getTable('Channel');
                channelTable.insert({ uri: channel.uri });
            });
    }

    function sendViewArticle(article) {
        var client = getMobileServiceClient();
        var item = { text: article.title, img: article.backgroundImage };
        client.getTable("MostViewed").insert(item);
    }

    function sendLocalTileNotification (article) {
        var notifications = Windows.UI.Notifications;

        var template = notifications.TileTemplateType.tileWideImageAndText01;
        var tileXml = notifications.TileUpdateManager.getTemplateContent(template);

        var tileTextAttributes = tileXml.getElementsByTagName("text");
        tileTextAttributes[0].appendChild(tileXml.createTextNode(article.title));

        var tileImageAttributes = tileXml.getElementsByTagName("image");
        tileImageAttributes[0].setAttribute("src", article.backgroundImage);
        tileImageAttributes[0].setAttribute("alt", article.title);

        var squareTemplate = notifications.TileTemplateType.tileSquareText04;
        var squareTileXml = notifications.TileUpdateManager.getTemplateContent(squareTemplate);
        var squareTileTextAttributes = squareTileXml.getElementsByTagName("text");
        squareTileTextAttributes[0].appendChild(squareTileXml.createTextNode(article.title));

        var node = tileXml.importNode(squareTileXml.getElementsByTagName("binding").item(0), true);
        tileXml.getElementsByTagName("visual").item(0).appendChild(node);

        var tileNotification = new notifications.TileNotification(tileXml);

        var currentTime = new Date();
        tileNotification.expirationTime = new Date(currentTime.getTime() + 600 * 1000);

        var tileUpdater = notifications.TileUpdateManager.createTileUpdaterForApplication();
        tileUpdater.enableNotificationQueue(true);
        tileUpdater.update(tileNotification);
    }

    function getMobileServiceClient() {
        var client = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
            "https://geekreader.azure-mobile.net/",
            "rsoaSnNYQYHGyHnqoosleYzvWgcCRH11"
        );
        return client;
    }

    WinJS.Namespace.define("TileNotification", {
        subscribeToPushNotification: subscribeToPushNotification,
        sendViewArticle: sendViewArticle,
        sendLocalTileNotification: sendLocalTileNotification,
    });

})();
